package mydb

import (
	"fmt"

	"jgt-wallet/src/model"
	"jgt-wallet/src/schema"
	"jgt-wallet/src/service/db"

	"github.com/facebookgo/inject"
	"github.com/pkg/errors"
)

// LogManageTableName 日志管理表名
const LogManageTableName = "s_log"

// LogManage 日志管理
type LogManage struct {
	DB *db.DB
}

// Init 初始化
func (a *LogManage) Init(g *inject.Graph, db *db.DB) {
	db.AddTableWithName(schema.LogManage{}, LogManageTableName)
	a.DB = db

	var val model.ILogManage = a
	g.Provide(&inject.Object{Value: val, Name: "ILogManage"})
}

// QueryPage 查询分页数据
func (a *LogManage) QueryPage(params schema.LogManageQueryParam, pageIndex, pageSize uint) (int64, []*schema.LogManageQueryResult, error) {
	var (
		args  []interface{}
		where = "WHERE 1=1"
		table = "s_log a"
	)

	if v := params.Type; v != "" {
		where = fmt.Sprintf("%s AND a.type=?", where)
		args = append(args, v)
	}

	if v := params.Level; v != "" {
		where = fmt.Sprintf("%s AND a.level=?", where)
		args = append(args, v)
	}

	if v := params.Message; v != "" {
		where = fmt.Sprintf("%s AND a.message LIKE ?", where)
		args = append(args, "%"+v+"%")
	}

	n, err := a.DB.SelectInt(fmt.Sprintf("SELECT count(*) FROM %s %s", table, where), args...)
	if err != nil {
		return 0, nil, errors.Wrapf(err, "查询分页数据发生错误")
	} else if n == 0 {
		return 0, nil, nil
	}

	query := fmt.Sprintf("SELECT a.record_id,a.type,a.level,a.message,a.data,a.creator,a.created FROM %s %s ORDER BY a.id DESC LIMIT %d,%d", table, where, (pageIndex-1)*pageSize, pageSize)

	var items []*schema.LogManageQueryResult
	_, err = a.DB.Select(&items, query, args...)
	if err != nil {
		return 0, nil, errors.Wrapf(err, "查询分页数据发生错误")
	}

	return n, items, err
}
